<template>
  <div>
    <BasicTable
      @register="registerTable"
      @resize-column="handleResizeColumn"
      :canResize="false"
      :scroll="{ x: 'max-content' }"
    >
      <template #toolbar>
        <a-button type="error" @click="handleDelete"> 批量删除 </a-button>
        <a-button type="success" @click="handleConponList">
          赠送优惠券
        </a-button>
        <a-button type="success" @click="handleGroup">调整分组</a-button>
        <a-button type="primary" @click="handleExport" :loading="exportLoading"
          >导出</a-button
        >
<!--        <a-button type="primary" @click="handleChart">查看图形分析</a-button>-->
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'headUrl'">
          <img style="width: 30px; height: 30px" :src="record.headUrl" />
        </template>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              color: 'success',
              label: '启用',
              ifShow: record.status == '1',
              popConfirm: {
                title: '确认要启用吗？',
                confirm: handleStopStart.bind(null, record.id),
              },
            },
            {
              color: 'error',
              label: '冻结',
              ifShow: record.status == '0',
              popConfirm: {
                title: '确认要冻结吗？',
                confirm: handleStopStart.bind(null, record.id),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <GroupModal @register="registerGroup" @success="handleSuccess" />
    <ConponModal @register="registerConpon" @success="handleSuccess" />
    <ChartModal @register="registerChart" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'ChargeManager',
});
</script>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { useModal } from '@/components/Modal';
import GroupModal from './components/GroupSelect.vue';
import ChartModal from './components/MemberChart.vue';
import ConponModal from './components/CouponSelect.vue';
import { columns, searchFormSchema } from './data';
import { useMessage } from '@/hooks/web/useMessage';
import { defHttp } from '@/utils/http/axios';
import { downloadBlob } from '@/utils/file/download';
const { createMessage } = useMessage();
const [registerChart, { openModal: openChartModal }] = useModal();
const [registerGroup, { openModal: openGroupModal }] = useModal();
const [registerConpon, { openModal: openConponModal }] = useModal();
const [
  registerTable,
  { reload, getForm, getSelectRows, getSelectRowKeys },
] = useTable({
  //title: '列表',
  api: '/admin/member/member',
  columns,
  showIndexColumn: true,
  useSearchForm: true,
  indexColumnProps: {
    fixed: 'left',
  },
  formConfig: {
    labelWidth: 70,
    hideLabel: true,
    schemas: searchFormSchema,
    baseColProps: { span: 6 },
  },
  pagination: true,
  bordered: true,
  actionColumn: {
    width: 50,
    title: '操作',
    dataIndex: 'action',
    slots: { customRender: 'action' },
    fixed: 'right',
  },
  rowKey: 'id',
  rowSelection: {
    type: 'checkbox',
  },
});
const emit = defineEmits(['success', 'register']);
const exportLoading = ref(false);
onMounted(() => {});

function handleConponList() {
  if (getSelectRows().length === 0) {
    createMessage.error('请选择要赠送的会员');
  } else {
    let memberIds = [];
    for (let a = 0; a < getSelectRows().length; a++) {
      memberIds.push(getSelectRows()[a].id);
    }
    openConponModal(true, {
      isUpdate: false,
      memberIds: memberIds,
    });
  }
}
function handleGroup(record: Recordable) {
  let ids = [];
  for (let a = 0; a < getSelectRows().length; a++) {
    ids.push(getSelectRows()[a].id);
  }
  openGroupModal(true, { ids: ids });
}
function handleChart() {
  openChartModal(true, {});
}
async function handleCoupon(param) {
  if (getSelectRows().length === 0) {
    createMessage.error('请选择要赠送的会员');
  } else {
    const res = await defHttp.post({
      url: `/admin/member/giveCoupons`,
      data: getSelectRowKeys(),
    });
    createMessage.success(res.message);
    reload();
  }
}
// async function handleExport(param) {
//   if (getSelectRows().length === 0) {
//     createMessage.error('请选择要赠送的会员');
//   } else {
//     const res = await defHttp.post({
//       url: `/admin/member/giveCoupons`,
//       data: getSelectRowKeys(),
//     });
//     createMessage.success(res.message);
//     reload();
//   }
// }
const handleExport = async () => {
  try {
    exportLoading.value = true;
    let param;
    if (getSelectRows().length > 0) {
      const ids = [];
      for (let a = 0; a < getSelectRows().length; a++) {
        ids.push(getSelectRows()[a].id);
      }
      debugger
      param = {
        ids: ids,
        importType: 'checkBox',
      };
    } else {
      param = {
        ...getForm().getFieldsValue(),
      };
    }
    const res = await defHttp.post(
      {
        url: '/admin/member/export',
        responseType: 'blob',
        data: JSON.stringify(param),
      },
      { isReturnNativeResponse: true },
    );
    downloadBlob(res);
  } catch (error) {
    console.log(error);
  } finally {
    exportLoading.value = false;
  }
};
async function handleStopStart(param) {
  const res = await defHttp.post({
    url: `/admin/member/memberStatus`,
    data: { id: param },
  });
  reload();
}
async function handleDelete() {
  if (getSelectRows().length === 0) {
    createMessage.error('请选择删除项');
  } else {
    const res = await defHttp.post({
      url: `/admin/member/deletes`,
      data: getSelectRowKeys(),
    });
    createMessage.success(res.message);
    reload();
  }
}
async function handleDeleteSingle(record: Recordable) {
  const res = await defHttp.post({
    url: `/admin/charge/deletes`,
    data: [record.id],
  });
  createMessage.success(res.message);
  reload();
}
function handleSuccess() {
  reload();
}
</script>
